//
//  VideoViewController.m
//  SnailPost
//
//  Created by 抠泥ser on 16/3/7.
//  Copyright © 2016年 抠泥ser. All rights reserved.
//

#import "VideoViewController.h"
#import "PrefixHeader.pch"
#import "VideoModel.h"
#import "VideoViewCell.h"
#import <MediaPlayer/MediaPlayer.h>
#import "VideoTypeCell.h"
#import "VideoTypeViewController.h"
#import "LHAFNetworkTool.h"
#import "PlayerManager.h"
@interface VideoViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong)UITableView *tableview; //tableView布置视频
@property (nonatomic, strong)NSMutableArray *dataArr; //保存数据数组
@property (nonatomic, assign)NSInteger number; //数字
@property (nonatomic, strong)NSMutableArray *Arr; //保存分类的数组
@property (nonatomic, strong)NSIndexPath *indexPath; //视频专用
@property (nonatomic, strong)MPMoviePlayerViewController *movieView;
@property (nonatomic, strong)UICollectionView *collection; // 视频分类点击
@property (nonatomic, strong)UIButton *button;
@property (nonatomic, strong) AppDelegate *appDelegate;

@end

@implementation VideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor =[UIColor whiteColor];
    self.navigationItem.title = @"视频";
  
    //点击tableView没有任何反应
//    self.tableview.userInteractionEnabled = NO;
    
    self.tableview = [[UITableView alloc]init];
    self.tableview.backgroundColor = [UIColor clearColor];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 90)];

    [self.view addSubview:_tableview];

    [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
     
    }];

    //注册重用池
    [_tableview registerClass:[VideoViewCell class] forCellReuseIdentifier:@"VideoCell"];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    
    layout.minimumLineSpacing = 0;
    //滚动方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    //cell大小
    layout.itemSize = CGSizeMake(self.view.frame.size.width / 4, 90);
    
    
//    创建collection
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 90) collectionViewLayout:layout];
//    self.collection = [[UICollectionView alloc]init];
//    _collection.collectionViewLayout = layout;
    _collection.backgroundColor =[UIColor clearColor];
    _collection.delegate = self;
    _collection.dataSource = self;

    
    //防止滚动
    _collection.scrollEnabled = NO;
    [self.tableview addSubview:_collection];

    //注册cell重用池
    [_collection registerClass:[VideoTypeCell class] forCellWithReuseIdentifier:@"cell"];
    
    //处理数据
    [self data];

    //下拉刷新
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(shuaxin)];
    
    
    
    //上拉加载
    MJRefreshAutoNormalFooter *footer =[MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loading)];
    self.tableview.mj_footer = footer;
    
    //下拉加载时的字
    [footer setTitle:@"正在加载中..." forState:MJRefreshStateRefreshing];
    
    //加载初始变化值
    self.number = 0;
    
}

- (void)data
{
    NSString *str =@"http://c.m.163.com/nc/video/home/0-10.html";
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *arr = resposeObject[@"videoList"];
        NSArray *arrb = resposeObject[@"videoSidList"];
        self.dataArr = [VideoModel modelHanderWithArray:arr];
        self.Arr = [VideoModel modelHanderWithArray:arrb];
        [_tableview reloadData];
        [_collection reloadData];
      
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
        
      

        
   
    
    
    
    //*****布置头部Button
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _Arr.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;

}

#pragma mark - CollectionView
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    VideoTypeCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    VideoModel *hi =_Arr[indexPath.row];
    [cell.img sd_setImageWithURL:[NSURL URLWithString:hi.imgsrc]placeholderImage:[UIImage imageNamed:@"mifeng"]];
    cell.name.text = hi.title;
    
    return cell;
}

#warning collectionView 的点击跳转
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    VideoTypeViewController *vc = [[VideoTypeViewController alloc]init];
    VideoModel *od = _Arr[indexPath.row];
    NSIndexPath *index = indexPath;
    vc.num = index;
    vc.hm = od;
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"VideoCell" forIndexPath:indexPath];
    VideoModel *hm =_dataArr[indexPath.row];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:hm.cover]placeholderImage:[UIImage imageNamed:@"mifeng"]];
    cell.title.text = hm.title;
    cell.content.text = hm.Description;
    cell.times.text = hm.length.stringValue;
    cell.counts.text = hm.playCount.stringValue;
    cell.backgroundColor = [UIColor clearColor];
    cell.hm = hm;
    
    CATransform3D rotation;//3D旋转
    
    rotation = CATransform3DMakeTranslation(0 ,50 ,20);
    //        rotation = CATransform3DMakeRotation( M_PI_4 , 0.0, 0.7, 0.4);
    //逆时针旋转
    
    rotation = CATransform3DScale(rotation, 0.9, .9, 1);
    
    rotation.m34 = 1.0/ -600;
    
    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    cell.layer.shadowOffset = CGSizeMake(10, 10);
    cell.alpha = 0;
    
    /**<  cell变化等于3d动画 */
    cell.layer.transform = rotation;
    
    [UIView beginAnimations:@"rotation" context:NULL];
    //旋转时间
    [UIView setAnimationDuration:0.6];
    cell.layer.transform = CATransform3DIdentity;
    cell.alpha = 1;
    cell.layer.shadowOffset = CGSizeMake(0, 0);
    [UIView commitAnimations];


    //选中cell的样式(当cell被点击时无任何点击背景颜色)
    cell.selectionStyle = UITableViewCellAccessoryNone;
    
    
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    cell.image.userInteractionEnabled = YES;
    [cell.image addGestureRecognizer:tap];
   
    return cell;
}
//点击图片触发的方法
-(void)tapAction:(UITapGestureRecognizer *)sender
{
    
    self.appDelegate = [UIApplication sharedApplication].delegate;
    _appDelegate.playerManager = [PlayerManager defaultManager];
    [_appDelegate.playerManager pause];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"zan" object:nil];
    
    //点开新的关闭旧的
    if (self.movieView.view) {
        [self.movieView.view removeFromSuperview];
    }
    //点击的哪个ImageView
    UIView *view = sender.view;
    //imageView->contentView->cell
    UITableViewCell *cell = (UITableViewCell *)view.superview.superview;
    
    //获取被点击的cell的indexPath
    self.indexPath = [self.tableview indexPathForCell:cell];
    
   VideoModel *video = _dataArr[_indexPath.row];
    self.movieView = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:video.mp4_url]];
   
    self.movieView.view.frame = CGRectMake(10, 55, self.view.frame.size.width - 25, [UIScreen mainScreen].bounds.size.height / 3.7);
    
    [UIView animateWithDuration:0.3 animations:^{
        
    self.movieView.view.frame = CGRectMake(0, 50, self.view.frame.size.width , [UIScreen mainScreen].bounds.size.height / 3.2);
        
    }];
    
    //设置全屏点击按键
    [self.movieView.moviePlayer setControlStyle:(MPMovieControlStyleEmbedded)];
  
    [cell addSubview:self.movieView.view];
    //    [_movieView release];
    //添加视频关闭按钮
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    [self.button setBackgroundImage:[UIImage imageNamed:@"cha"] forState:UIControlStateNormal];
    [self.movieView.view addSubview:self.button];
    //设置按钮的相对坐标
    [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.movieView.view).with.offset(-5);
        make.top.equalTo(self.movieView.view.mas_top).with.offset(5);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
}

//通知中心 让视频停掉
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.movieView.view) {
        //        self.movieView.moviePlayer.pause;
        [self.movieView.view removeFromSuperview];
    }
}
//"x"按钮实现方法
- (void)close:(UIButton *)btn
{
    [self.movieView.moviePlayer stop];
    [self.movieView.moviePlayer pause];
    [self.movieView.view removeFromSuperview];
}




//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//
//    //让选中的灰色状态栏消失掉
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 310;
}

//下拉刷新
- (void)shuaxin
{
    [self.tableview.mj_header beginRefreshing];
    NSString *str =@"http://c.m.163.com/nc/video/home/0-10.html";

    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *arr = resposeObject[@"videoList"];
        NSArray *arrb = resposeObject[@"videoSidList"];
        self.dataArr = [VideoModel modelHanderWithArray:arr];
        self.Arr = [VideoModel modelHanderWithArray:arrb];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
   
    }];
         //拿到当前的下拉刷新,结束刷新
    [self.tableview.mj_header endRefreshing];
}


//实现上拉加载
- (void)loading
{
    _number +=10;
    //开始加载
    [_tableview.mj_footer beginRefreshing];
    
   
    [LHAFNetworkTool getUrl:[NSString stringWithFormat:@"http://c.m.163.com/nc/video/home/%ld-10.html",(long)_number] body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        
        NSArray *arr = resposeObject[@"videoList"];
        arr = [VideoModel modelHanderWithArray:arr];
        for (NSInteger i =0; i < arr.count; i++) {
            [_dataArr addObject:arr[i]];
        }
        
        [_tableview reloadData];
       
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    [self.tableview.mj_footer endRefreshing];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
